package com.xstudio.pvzreborn.utils.registry;

import com.xstudio.pvzreborn.event.custom.PVZRegistryEvent;
import com.xstudio.pvzreborn.event.custom.PVZRegistryEvent.Kind;
import com.xstudio.pvzreborn.item.ItemManager;
import com.xstudio.pvzreborn.utils.registry.holder.ItemHolder;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Item.Properties;
import net.minecraftforge.registries.RegistryObject;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.LinkedHashMap;

public class ItemRegistrationHelper extends RegistrationHelper<Properties, Item> {

    private boolean isRegisteringBlockItem;

    public ItemRegistrationHelper(@NotNull String groupName, RegistrationAction<Properties, Item> defaultRegistryAction, boolean orderly) {
        super(groupName, orderly ? new LinkedHashMap<>() : new HashMap<>(), defaultRegistryAction);
    }

    public ItemRegistrationHelper(String groupName, RegistrationAction<Properties, Item> defaultRegistryAction) {
        this(groupName, defaultRegistryAction, false);
    }

    public ItemRegistrationHelper(String groupName, boolean orderly) {
        this(groupName, null, orderly);
    }

    public ItemRegistrationHelper(String groupName) {
        this(groupName, null, false);
    }

    public boolean isRegisteringBlockItem() {
        return this.isRegisteringBlockItem;
    }

    public ItemRegistrationHelper setRegisteringBlockItem() {
        this.isRegisteringBlockItem = true;
        return this;
    }

    /**
     * @param itemName 待注册物品的名称
     * @param supplier 注册行为, 决定该物品如何注册
     */
    @Override
    public ItemRegistrationHelper addElement(String itemName, RegistrationAction<Properties, ? extends Item> supplier) {
        registry.put(itemName, new ItemHolder(itemName, supplier));
        previousName = itemName;
        return this;
    }

    @Override
    public ItemRegistrationHelper properties(Properties properties) {
        super.properties(properties);
        return this;
    }

    @Override
    public ItemRegistrationHelper addElement(String name) {
        super.addElement(name);
        return this;
    }

    @Override
    public void register() {
        registry.forEach((itemName, holder) -> {
            Kind kind = isRegisteringBlockItem ? Kind.BlockItem : Kind.Item;
            PVZRegistryEvent.Pre<? extends Item> pre = new PVZRegistryEvent.Pre<>(kind, Item.class, itemName, groupName, holder.getSupplier());
            if (!pre.postModBus()) {
                RegistryObject<? extends Item> item = ItemManager.ITEM_REGISTRY.register(itemName, pre.getSupplier());
                new PVZRegistryEvent.Post<>(kind, Item.class, itemName, groupName, item).postModBus();
            }
        });
    }

}
